home *** CD-ROM | disk | FTP | other *** search
- Path: mayne.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Reusable and Generic Functions
- Date: 21 Apr 1996 10:56:56 -0700
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4ldst8INNlub@mayne.ugrad.cs.ubc.ca>
- References: <4la9k2$76o@wormer.fn.net>
- NNTP-Posting-Host: mayne.ugrad.cs.ubc.ca
-
- In article <4la9k2$76o@wormer.fn.net>,
- Rusty Meathook <withheld@keepitpublic.com> wrote:
- >Suppose a guy has two linked list structures, such as:
- >
- >/* Untested code based on previously written tested code :) */
- >
- >typedef struct foo_tag
- >{
- > int data;
- > struct foo_tag *next;
- >} FOO;
- >
- >typedef struct bar_tag
- >{
- > float data;
- > struct bar_tag *next;
- >} BAR;
- >
- >/* */
- >
- >Is there a simple way to handle operations on both of those lists
- >using the same set of functions? Say for adding links we have this
- >function:
-
- Yes, but not in this manner. The proper C way of doing that would be to define
- a single list type item like this:
-
- union generic {
- double *d;
- long l;
- unsigned long u;
- void *p;
- };
-
- typedef struct listnode_tag {
- union generic e;
- struct listnode_tag *next;
- } listnode;
-
- Now, you can store a pointer as listnode.e.p, a double as listnode.e.d and so
- forth.
-
-
- >/* Untested code based on previously written tested code :) */
- >
- >FOO *sllist_add(FOO *next, int data)
- >{
- > FOO *temp;
-
-
- This would be written as:
-
- listnode *sllist_add(listnode *next, union generic data)
-
- {
- /* ... */
-
- temp->data = data; /* struct/union assignment */
-
- return temp;
- }
-
-
- What do you think? The above is not super slick, but you could define
- ``alternate access'' functions to complement it:
-
- listnode *sllist_add_ptr(listnode *next, void *ptr)
-
- {
- union generic data;
-
- data.e.p = ptr;
-
- /* ... and so forth */
- }
-
- It's up to the client code module to implement a discipline which will prevent
- it from storing an item as one type, and referencing it later as another type.
- A good rule of thumb would be to not store more than one type into any one
- distinct list.
-